package com.example.demo.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class LogControllerAspect {
    private final Logger logger= LoggerFactory.getLogger(LogControllerAspect.class);

    @Pointcut("execution(* com.example.demo.controller..*.*(..))")
    public void addAdvice(){};

    /***
     * 切面之前
     */
    @Before("addAdvice()")
    public void doBefore(JoinPoint joinPoint){
        //获取HttpServletRequest
        HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String url=request.getRequestURI();
        String ip=request.getRemoteAddr();
        String classMethod=joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        Object[] args=joinPoint.getArgs();
        RequestInfo requestInfo=new RequestInfo(url,ip,classMethod,args);
        logger.info("doBefore ---->" + requestInfo);
    }

    /**
     * 切面之后
     */
    @After("addAdvice()")
    public void doAfter(){
        logger.info("--------doAfter----------");
    }

    /**
     * 获取返回值
     */
    @AfterReturning(pointcut = "addAdvice()",returning = "obj")
    public void doAfterReturn(Object obj){
       logger.info("Return  ---> " + obj);
    }

    /**
     * 定义局部内部类 封装日志信息
     */
    private class RequestInfo{
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestInfo(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
